package cn.krund.lyc.hotlerobot.Ros.service.communication;

import java.io.DataInputStream;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @包名: cn.krund.lyc.hotlerobot.Ros.service.communication
 * @作者: 刘育成
 * @时间: 2018/4/8  11:03
 * @org: 克路德人工智能
 * @描述: TODO  Ros端通讯socket
 * @fileName: RosSocketRunnable
 */

public class RosSocketRunnable extends CommunicationRunnable {
    private static ExecutorService sendMessageToClientThreadPool = Executors.newSingleThreadExecutor();  // 发送信息到客户端用的线程池
    private IRosCommunicationListener mRosCommunicationListener;

    public RosSocketRunnable(Socket socket, IRosCommunicationListener communicationListener) {
        super(socket, communicationListener);
        this.mRosCommunicationListener=communicationListener;
    }

    @Override
    protected void socketHandler(Socket socket) throws Exception {
        super.RosSocket=socket;
        //这个需要修改
        NetProtocolPretreatment netProtocolPretreatment = new NetProtocolPretreatment();            // 网络协议预处理类
        DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
        byte[] buffer = new byte[1024];
        while (socket.isConnected() && !socket.isClosed()) {
            int readLen = dataInputStream.read(buffer);
            if (readLen > 0) {
                netProtocolPretreatment.getNetProtocol(buffer, readLen, mRosCommunicationListener);
                this.sendRosMessageToClient(buffer, 0, readLen);
            }
        }
    }
    /**
     * 发送Ros信息给客户端
     *
     * @param datas
     * @param dataOffset
     * @param dataSize
     */
    private void sendRosMessageToClient(byte[] datas, int dataOffset, int dataSize) {
        for (Socket socket : phoneSockets) {
            if (socket == null || socket.isClosed()) continue;
            sendMessageToClientThreadPool.execute(
                    new SendMessageToClientRunnable(socket, datas, dataOffset, dataSize));
        }
    }
}
